<template>
  <div class="login">
    <van-form @submit="onSubmit">
      <van-field v-model="username" name="uname" label="用户名" placeholder="请输入" />
      <van-field v-model="password" type="password" name="upass" label="密码" placeholder="请输入" />

      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>

      <div>
        <router-link class="link" to="/register">还没账号，立即注册?</router-link>
      </div>

      <div class="message">
        <van-checkbox v-model="checked" icon-size="12px"></van-checkbox>
        阅读并同意美了么外卖的
        <a href="#">《服务协议》</a>
        <a href="#">《个人信息保护政策》</a>
        未注册手机号将自动注册
      </div>
    </van-form>
  </div>
</template>

<script>
// 导入组件
import { Toast, Dialog } from 'vant'

export default {
  data() {
    return {
      username: '',
      password: '',
      checked: false,
      sky_users: JSON.parse(localStorage.getItem("SKY_USERS")) || [],
    };
  },
  methods: {
    onSubmit() {
      if (!this.checked) {
        Toast('请阅读协议和政策');
        return;
      }

      const { username, password } = this;
      if (!username || !password) {
        Toast('输入框不能为空~');
        return;
      }

      const user = this.sky_users.find(item => item.username === username && item.password === password);

      if (user) {
        localStorage.setItem("AUTO_TOKEN", user.id);
        localStorage.setItem("SKY_USERNAME", user.username);

        Dialog.alert({
          confirmButtonColor: "#0c8bf3",
          message: '登录成功。',
        }).then(() => {
          this.$router.push({ path: '/my' });
        });
      } else {
        const userExists = this.sky_users.some(item => item.username === username);
        Toast(userExists ? '账号或者密码错误' : '该账号不存在');
      }
    },
  },
};
</script>


<style lang="less" scoped>

.login {
  padding-top: 150px;

  .van-button--normal {
    background-color: #1EC28A;
    border: 0;
  }

  .link {
    display: block;
    width: 100%;
    text-align: center;
    font-size: 16px;
    // text-decoration: underline;

  }

  .message {
    padding: 0 15px;
    box-sizing: border-box;
    margin-top: 20px;
    font-size: 13px;
    font-family: Arial, Helvetica, sans-serif;
    font-weight: normal;
    text-align: center;
    color: #666;
    line-height: 175%;

    a {
      color: #0c8bf3;
    }

    .van-checkbox {
      display: inline-block !important;
    }
  }

}
</style>
